<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

class Draw extends Base
{
    protected $type = [
        'examine_time' => 'timestamp'
    ];

    protected function user(): object
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,photo');
    }

    protected function getAccountAttr($value): string
    {
        return get_pay_way($value);
    }

    protected function getModeAttr($value): string
    {
        return get_pay_way($value);
    }

    protected function getBankNumberAttr($value): string
    {
        return $value . "\t";
    }

    protected function getStatusNameAttr($value, $data): string
    {
        return getExamineStatus($data['status']);
    }

    public static function _save($param, $logs): array
    {
        parent::startTrans();
        try {
            if (empty($param['status'])) {
                throw new \Exception('请选择审核类型');
            }
            $info = parent::where(['id' => $param['id']])->find();
            if (empty($info)) {
                throw new \Exception('该申请不存在');
            }
            if ($info->getData('status') != 1) {
                throw new \Exception('该记录已审核，请勿重复审核！');
            }
            if ($param['status'] == 2) {
                $info->reject_msg = '';
                $msg = '通过提现申请，标识ID【' . $param['id'] . '】，会员【' . $info->user->id . '】【' . $info->user->code . '】';
            } else {
                $info->reject_msg = $param['reject_msg'];
                $msg = '驳回提现申请，标识ID【' . $param['id'] . '】，会员【' . $info->user->id . '】【' . $info->user->code . '】';
                Target::Account()->basics($info->uid, $info->getData('account'), $info->amount, '提现驳回', '+')
                    ->createNormal();
            }
            $info->status = $param['status'];
            $info->admin_id = $logs['admin']->id;
            $info->admin_name = $logs['admin']->admin_name;
            $info->examine_time = time();
            $info->save();
            Logs::adds($msg, $logs['admin']->id, $logs['admin']->admin_name);

            parent::commit();
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '已审核'];
    }

    public static function batchPass($ids, $admin): array
    {
        parent::startTrans();
        try {
            $list = parent::where(['status' => 1])->whereIn('id', array_values($ids))->select();
            if ($list->isEmpty()) {
                throw new \Exception('未查询到待审核的数据，请检查！');
            }
            $new_ids = [];
            foreach ($list as $item) {
                $new_ids[] = $item->id;
            }
            if ($new_ids) {
                parent::update(
                    ['status' => 2, 'examine_time' => time(), 'admin_id' => $admin->id, 'admin_name' => $admin->admin_name],
                    ['id' => $new_ids]
                );
                $msg = '批量通过提现申请,标识ID【' . implode(',', $new_ids) . '】';
                Logs::adds($msg, $admin->id, $admin->admin_name);
            }

            parent::commit();
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '已批量通过'];
    }

    public static function batchReject($ids, $admin): array
    {
        parent::startTrans();
        try {
            $list = parent::where(['status' => 1])->whereIn('id', array_values($ids))->select();
            if ($list->isEmpty()) {
                throw new \Exception('未查询到待审核的数据，请检查！');
            }
            $new_ids = [];
            foreach ($list as $item) {
                Target::Account()->basics($item->uid, $item->getData('account'), $item->amount, '提现驳回', '+')
                    ->createNormal();
                $new_ids[] = $item->id;
            }
            if ($new_ids) {
                parent::update(
                    ['status' => 3, 'examine_time' => time(), 'admin_id' => $admin->id, 'admin_name' => $admin->admin_name],
                    ['id' => $new_ids]
                );
                $msg = '批量驳回提现申请,标识ID【' . implode(',', $new_ids) . '】';
                Logs::adds($msg, $admin->id, $admin->admin_name);
            }

            parent::commit();
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '已批量驳回'];
    }

    public static function add($param, $user, $system): array
    {
        parent::startTrans();
        try {
            if (!$system['draw_open']) {
                throw new \Exception('提现功能已关闭');
            }
            $week = explode(',', $system['draw_week']);
            if (!in_array(date('w'), $week)) {
                throw new \Exception('今日不可提现');
            }
            $times = explode(',', $system['draw_times']);
            $his = date('H:i:s');
            if ($his < $times[0] || $his > $times[1]) {
                throw new \Exception('每日提现时间为：' . $times[0] . ' ~ ' . $times[1]);
            }
            if ($system['draw_min'] > $param['amount']) {
                throw new \Exception('最低提现金额：' . $system['draw_min']);
            }
            if ($system['draw_bs']) {
                if ($param['amount'] % $system['draw_bs'] != 0) {
                    throw new \Exception('提现倍数：' . $system['draw_bs']);
                }
            }
            $count = parent::where(['uid' => $user->id])->whereDay('create_time')->count();
            if ($count >= $system['draw_day']) {
                throw new \Exception('每日只可提现' . $system['draw_day'] . '次');
            }
            if (md5($param['pay_password']) != $user->pay_password) {
                throw new \Exception('支付密码错误');
            }
            $account = $param['account'];
            if ($param['amount'] > $user->assets->$account) {
                throw new \Exception(get_pay_way($account) . '账户余额不足');
            }
            switch ($param['mode']) {
                case 'wechat':
                    if (!$user->wechat_image) {
                        throw new \Exception('请完善' . get_pay_way('wechat') . '收款方式');
                    }
                    $param['wechat_name'] = $user->wechat_name;
                    $param['wechat_image'] = $user->wechat_image;
                    break;
                case 'alipay':
                    if (!$user->alipay_image) {
                        throw new \Exception('请完善' . get_pay_way('alipay') . '收款方式');
                    }
                    $param['alipay_name'] = $user->alipay_name;
                    $param['alipay_image'] = $user->alipay_image;
                    break;
                default:
                    if (!$user->bank_number) {
                        throw new \Exception('请完善' . get_pay_way('bank') . '收款方式');
                    }
                    $param['bank_name'] = $user->bank_name;
                    $param['bank_account_name'] = $user->bank_account_name;
                    $param['bank_number'] = $user->bank_number;
                    $param['bank_open'] = $user->bank_open;
            }
            $cost = 0;
            if ($system['draw_cost'] && $system['draw_cost'] > 0) {
                $cost = round($param['amount'] * $system['draw_cost'], 2);
            }
            $param['uid'] = $user->id;
            $param['cost'] = $cost;
            $param['real_amount'] = round($param['amount'] - $cost, 2);
            parent::create($param);
            Target::Account()->basics($user->id, $account, $param['amount'], '提现', '-')
                ->createNormal();

            parent::commit();
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '申请已提交，请耐心等待审核'];
    }
}